// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ControllerStateMachine.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Manipulation.ControllerStateMachine
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Defines a controller state machine
    /// </summary>
    public class ControllerStateMachine
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ControllerStateMachine"/> class.
        /// </summary>
        public ControllerStateMachine()
        {
            this.HaltState = null;
            this.HaltTransitions = null;
            this.States = new List<State>();
        }

        /// <summary>
        /// Gets or sets states of the controller state machine.
        /// </summary>
        public List<State> States { get; set; }

        /// <summary>
        /// Gets or sets halting state.
        /// </summary>
        public State HaltState { get; set; }

        /// <summary>
        /// Gets or sets default transitions to halting state from every other state (unless otherwise indicated in state definition).
        /// </summary>
        public Transition[] HaltTransitions { get; set; }
 
        /// <summary>
        /// Gets or sets generates a controller state machine description from the current ControllerStateMachine
        /// </summary>
        /// <returns>A controller state machine description</returns>
        public ControllerStateMachineDescription ToControllerStateMachineDescription()
        {
            int stateNum = 0;

            List<ControllerState> controllerStateMachineStates = new List<ControllerState>();

            List<ControllerTransition> haltTransitions = new List<ControllerTransition>();

            int haltStateID = -1;

            // Assign IDs to all non-halt states
            // The start state will be the first state in the list,
            // otherwise order doesn't matter
            for (int i = 0; i < this.States.Count; ++i)
            {
                this.States[i].Id = stateNum++;
            }

            // build a list of halt transitions
            if (this.HaltState != null && this.HaltTransitions.Length > 0)
            {
                haltStateID = stateNum++;

                // build transition list
                foreach (Transition t in this.HaltTransitions)
                {
                    haltTransitions.Add(new ControllerTransition(
                        haltStateID,
                        t.TestOpCode,
                        t.Operands,
                        new OperationList(t.Operations)));
                }
            }

            // Build each state
            foreach (State s in this.States)
            {
                List<ControllerTransition> transitions = new List<ControllerTransition>();

                // apply transitions to be evaluated before defaults
                foreach (Transition t in s.TransitionsToEvaluateBeforeDefaults)
                {
                    transitions.Add(
                        new ControllerTransition(
                            t.TargetState.Id,
                            t.TestOpCode,
                            t.Operands,
                            new OperationList(t.Operations)));
                }

                // apply default transitions if applicable
                if (s.ApplyHaltTransitions)
                {
                    transitions.AddRange(haltTransitions);
                }

                // build a transition list
                foreach (Transition t in s.TransitionsToEvaluateAfterDefaults)
                {
                    transitions.Add(
                        new ControllerTransition(
                            t.TargetState.Id,
                            t.TestOpCode,
                            t.Operands,
                            new OperationList(t.Operations)));
                }

                controllerStateMachineStates.Add(new ControllerState(
                    s.ControlMode,
                    s.Id,
                    new OperationList(s.Operations),
                    transitions.ToArray()));
            }

            if (haltStateID != -1)
            {
                // add a fault state to the description
                controllerStateMachineStates.Add(new ControllerState(
                    this.HaltState.ControlMode,
                    haltStateID,
                    new OperationList(this.HaltState.Operations),
                    new List<ControllerTransition>().ToArray()));
            }

            return new ControllerStateMachineDescription(controllerStateMachineStates.ToArray());
        }
    }
}
